// pages/messageDetail/messageDetail.js
import * as socketUtil from'../../api/socketUtil'
import * as API_Upload from '../../utils/fileUpload'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum:1,
    pageSize:10,
    msgContent:"",
    memberId:"",
    msgList:[],
    leftHead:"",
    rightHead:"",
    maxId:0,
    showMoreMgs:true,
    lastTime:null,
    showSendBtn:false

  },
  msgContentInput:function(e){
    let content=e.detail.value;
    if(content&&content.length>0){
      this.setData({showSendBtn:true});
    }else{
      this.setData({showSendBtn:false});
    }
  },
  uploadImg: function (e) {
    
    var that = this;
    wx.showActionSheet({
     itemList: ['相册', '相机'],
     itemColor: "#40ba67",
     success: function (res) {
      if (!res.cancel) {
       if (res.tapIndex == 0) {
        that.chooseWxImageShop('album')
       } else if (res.tapIndex == 1) {
        that.chooseWxImageShop('camera')
       }
      }
     }
    })
   },
   chooseWxImageShop: function (type) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        that.setData({contactsQrcode:res.tempFilePaths[0]})
        API_Upload.upload(that.data.contactsQrcode,res=>{
            const {url} = JSON.parse(res.data);
            that.sendSocketMsg(url,"img");
        },res=>{
          
            wx.showToast({
                title:'发送失败',
                icon:'none'
            })
        })
      }
    })
  },
  sendImageMsg:function(){

  },
  hasReadMsg:function(){
    let reqParam={storeId:this.data.store.id,memberId: this.data.memberId} ;
    socketUtil.sendData("UPDATE_READ_STATUS",reqParam);
  },
  moreMsg:function(){
    let csId;
    if(this.data.maxId>0){
      csId=this.data.maxId;
    }

    let reqParam={pageNum:this.data.pageNum,pageSize:this.data.pageSize,csId:csId,storeId:this.data.store.id,memberId: this.data.memberId} ;
    
    socketUtil.sendData("DIALOG_BY_LIST",reqParam);
    this.setData({
      pageNum:this.data.pageNum+1,rows:this.data.rows
    })
    this.setData({
      showMoreMgs:false
    })
   
  },
  
  sendMsg:function(e){
     let content= e.detail.value.textarea;
     if(!content){
       return;
     }
     this.setData({msgContent:"",showSendBtn:false});
    this.sendSocketMsg(content,"text");
    
  },
  sendSocketMsg:function(content,msgType){
    let msgJson={content:content,typeName:'right',msgType:msgType};
    this.addOneMsg(msgJson);
    let reqParam={content:content,msgType:msgType,storeId:this.data.store.id,receiveId: this.data.memberId} ;
     socketUtil.sendData("SEND_MSG",reqParam);
  },
  addOneMsg:function(json){
    
    let list=this.data.msgList;
    list.push(json);
    this.setData({msgList:list})
    this.pageScrollToBottom();
  },
  RECEIVE_MSG_INFORM:function(json){
    //收到新消息
    
    let msgJson={content:json.info.content,typeName:'left',msgType:json.info.msgType};
    this.addOneMsg(msgJson);
    this.hasReadMsg();
  },
  DIALOG_BY_LIST: function (json){
  console.log("收到变化"+json);
     //获取历史消息
     let tableDataInfo=json.info.tableDataInfo;
     let list=tableDataInfo.rows;
    
     
    //  let totalPages=json.info.page.totalPages;
     
    
     let otherNickName=json.info.otherNickName;
    let leftHead=json.info.otherHeadImg;
    
     let rightHead=this.data.store.storeImage;
     this.setData({otherNickName:otherNickName,leftHead:leftHead,rightHead:rightHead});
     list.forEach(element => {
       if('Y'==element.tostoreState){
         element.typeName='left';
       }else{
         element.typeName='right';
       }
       let sendTime=element.createTime;//当前消息的发送时间
       if((this.data.lastTime-sendTime)>5*60*1000){
            //时间差超过几分钟才才显示时间
            let dateStr=this.formatDate(this.data.lastTime);
            let timeJson={typeName:'time',content:dateStr};
            this.data.msgList.unshift(timeJson);
       }
       this.data.msgList.unshift(element);
       this.setData({lastTime:sendTime})
     
     });
     //this.data.msgList=this.data.msgList.unshift(list);
     
     
     let showMoreMgs=false;
     if(this.data.pageNum>tableDataInfo.pages){
       showMoreMgs=false;
       
       let size=list.length;
       if(size>0){
        let lastCreateTime=list[size-1].createTime;
        if(!lastCreateTime!=this.data.lastTime){
           let dateStr=this.formatDate(lastCreateTime);
           let timeJson={typeName:'time',content:dateStr};
           this.data.msgList.unshift(timeJson);
        }
       }
    }else{
      showMoreMgs=true;
    }
    
    this.setData({
      showMoreMgs:showMoreMgs, msgList:this.data.msgList
    })

     if(this.data.maxId==0){
      //为避免获取历史消息重复，初次进入页面获取当前最大的id，每次根据最大的id分页
     if(list.length>0){
       let msg=list[0];
       this.data.maxId=msg.id;
     }
     this.pageScrollToBottom();
    }
    
    },
    formatDate:function (date){
      
      date = new Date(date);
      var y=date.getFullYear();
      var m=date.getMonth()+1;
      var d=date.getDate();
      var h=date.getHours();
      var m1=date.getMinutes();
      var s=date.getSeconds();
      m = m<10?("0"+m):m;
      d = d<10?("0"+d):d;
      h = h<10?("0"+h):h;
      m1 = m1<10?("0"+m1):m1;
      s = s<10?("0"+s):s;
      let ymd=y+"-"+m+"-"+d;
      let time=h+":"+m1+":"+s;
      let nowDateymd=this.formatDateYMD();
      if(nowDateymd==ymd){
        //是今天的只显示时间
        return time;
      }else{
        //返回完整时间
        return ymd+" "+time;
      }
      
  },
  formatDateYMD:function (){
    var date = new Date();
    var y=date.getFullYear();
    var m=date.getMonth()+1;
    var d=date.getDate();
    var h=date.getHours();
    var m1=date.getMinutes();
    var s=date.getSeconds();
    m = m<10?("0"+m):m;
    d = d<10?("0"+d):d;
    let ymd=y+"-"+m+"-"+d;
  
    return ymd;
},
    pageScrollToBottom: function () {
      
  
      wx.createSelectorQuery().select('#messageview').boundingClientRect(function (rect) {
        //that.setData({scrollTop:rect.bottom});
        // 使页面滚动到底部
        wx.pageScrollTo({
          scrollTop: rect.height,
          duration: 300
        })
      }).exec()
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let store=wx.getStorageSync('store');
   
    var memberId=options.memberId;//与我对话用户的id
 
    this.setData({store:store,memberId:memberId})
    this.hasReadMsg();
    this.moreMsg();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().watch(this.DIALOG_BY_LIST,'DIALOG_BY_LIST')//注册监听
    getApp().watch(this.RECEIVE_MSG_INFORM,'RECEIVE_MSG_INFORM')//注册监听
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})